package com.ruoyi.base.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 主要用来接收和处理订阅主题的消息
 */
public class SubscribeCallBack implements MqttCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(SubscribeCallBack.class);

    private MqttServer mqttServer;

    public SubscribeCallBack(MqttServer server) {
        mqttServer = server;
    }

    // 连接丢失的操作
    public void connectionLost(Throwable cause) {

        LOGGER.info("***************订阅断开，正在重连");

        mqttServer.subscribeConnect();

        MqttClient client = mqttServer.getSubscribeClient();
        while (!client.isConnected()){
            try {
                LOGGER.info("***************重连失败，5秒后重试");
                Thread.sleep(5000);
                mqttServer.subscribeConnect();
            }catch (Exception ignored){
            }
        }

    }



    //接收订阅的消息
    public void messageArrived(String topic, MqttMessage message) throws Exception {

        String result = new String(message.getPayload(),"UTF-8");
        System.out.println("主题 : " + topic);
        System.out.println("Qos : " + message.getQos());
        System.out.println("内容 : " + result);

        //消息处理

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

}
